package com.wbao.dianniu.im;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.OnRefreshListener;
import com.wbao.dianniu.adapter.UserInfoHolder;
import com.wbao.dianniu.data.NoticeHandData;
import com.wbao.dianniu.listener.IFriendConfirmListener;
import com.wbao.dianniu.listener.INoticeHandListListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.ChatNotifyReadManager;
import com.wbao.dianniu.manager.FriendConfirmManager;
import com.wbao.dianniu.manager.NoticeHandListManager;
import com.wbao.dianniu.ui.BaseActivity;
import com.wbao.dianniu.update.ChatUnreadChangeManger;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.R;
import com.wbao.dianniu.utils.Utils;

/**
 * 待办事项
 *
 * @author yejianjun
 */
public class AgentActivity extends BaseActivity implements IFriendConfirmListener, INoticeHandListListener {
    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;
    private PullToRefreshListView pullListView;
    private ListView mListView;
    private FriendConfirmManager fcManager;
    private AgentAdapter adapter;
    private List<NoticeHandData> mList;
    private NoticeHandListManager manager;
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private ChatNotifyReadManager chatNotifyReadManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_agents, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        initWattingView();
        init();
        requestData(currentPage);
        chatNotifyReadManager = new ChatNotifyReadManager(this);
        chatNotifyReadManager.chatNotifyRead(117);
        ChatUnreadChangeManger.getInstance().chatUnreadChange(117,0);
        int unread = getIntent().getIntExtra(Const.BUNDLE_COUNT,0);
        String title = getIntent().getStringExtra(Const.BUNDLE_POST);
        setTitleName(title == null ? "" : title);
        ChatUnreadChangeManger.getInstance().minusNotifyUnread(unread);
//        YWIMKit iMkit = LoginSampleHelper.getInstance().getIMKit();
//        IYWConversationService conversationService = iMkit.getConversationService();
//        YWConversation conversation = conversationService.getConversationByUserId("117", LoginSampleHelper.APP_KEY);
//        if (null != conversation)
//            conversationService.markReaded(conversation);
    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
    }

    private void init() {
        pullListView = findViewById(R.id.agent_listview);
        pullListView.setMode(Mode.PULL_UP_TO_REFRESH);
        pullListView.setOnRefreshListener(onRefreshListener);
        mListView = pullListView.getRefreshableView();
        registerForContextMenu(mListView);

        adapter = new AgentAdapter(this);
        mList = new ArrayList<>();
        adapter.addData(mList);
        mListView.setAdapter(adapter);
    }

    OnRefreshListener onRefreshListener = new OnRefreshListener() {

        @Override
        public void onRefresh() {
            // 上拉刷新 加载请求数据
            pullUpRequest();
        }
    };

    // 上拉刷新数据请求
    private void pullUpRequest() {
        //没有搜索结果 或者数据为空 上拉没有效果
        ++currentPage;
        requestData(currentPage);
    }

    private void requestData(int page) {
        manager = new NoticeHandListManager(this);
        manager.addNoticeHandListListener(this);
        manager.noticeHandList(GlobalContext.getAccountId(), page * PAGE_COUNTS, PAGE_COUNTS);
    }

    /**
     * @param friendId friendId
     * @param status
     */
    private void confirm(int friendId, int status) {
        fcManager = new FriendConfirmManager(this);
        fcManager.addFriendConfirmListener(this);
        fcManager.confirm(GlobalContext.getAccountId(), friendId, status);
    }

    class AgentAdapter extends BaseAdapter {

        private Context mContext;
        private List<NoticeHandData> list;
        private LayoutInflater mInflater;
        private final int TYPE_APPROVAL = 1;
        private final int TYPE_AGREED = 2;
        private final int TYPE_REFUSED = 3;
        private final int TYPE_REFUSED_NOTIFY = 4;

        public AgentAdapter(Context context) {
            mContext = context;
            mInflater = LayoutInflater.from(mContext);
            if (null == list) {
                list = new ArrayList<NoticeHandData>();
            }
        }

        public void addData(List<NoticeHandData> addList) {
            for (int i = 0; i < addList.size(); i++) {
                list.add(addList.get(i));
            }
        }

        public List<NoticeHandData> getList() {
            return list;
        }

        @Override
        public int getCount() {
            if (null == list)
                return 0;
            else
                return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder holder = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.agent_list_item, null);
                holder = new Holder();
                holder.titile = convertView.findViewById(R.id.agent_list_title);
                holder.headIV = convertView.findViewById(R.id.user_head);
                holder.nameTV = convertView.findViewById(R.id.user_name);
                holder.labelTV = convertView.findViewById(R.id.user_label);
                holder.sexIV = convertView.findViewById(R.id.user_sex);
                holder.partnerIV = convertView.findViewById(R.id.user_partner);
                holder.addV = convertView.findViewById(R.id.add_v_iv);
                holder.headInfoLayout = convertView.findViewById(R.id.user_head_layout);
                holder.confirm = convertView.findViewById(R.id.agreed_tv);
                holder.cancel = convertView.findViewById(R.id.refused_tv);
                holder.agentLayout = convertView.findViewById(R.id.agent_pending_layout);
                holder.alreadyTV = convertView.findViewById(R.id.already_pending_tv);
                holder.refusedTV = convertView.findViewById(R.id.already_refused_desc);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            final NoticeHandData data = list.get(position);

            PictureDownloadUtils.displayHeadImage(mContext, holder.headIV, data.getHeadPic());
            holder.nameTV.setText(data.getRealName() == null ? "" : data.getRealName());
            holder.labelTV.setText(data.getLabel() == null ? "" : data.getLabel());
            Utils.showSex(mContext, data.getUserInfo().sex, holder.sexIV);
            Utils.showPartner(mContext,data.getUserInfo().partner,holder.partnerIV);
            Utils.showAuth(data.getUserInfo(), holder.addV);
            int type = data.getStatus();
            if (type == TYPE_APPROVAL) {
                holder.titile.setText(getResources().getString(R.string.add_friend_apply));
                holder.agentLayout.setVisibility(View.VISIBLE);
                holder.alreadyTV.setVisibility(View.GONE);
                holder.refusedTV.setVisibility(View.GONE);
                holder.confirm.setOnClickListener(new MyClickListener(1, data.getAccountId(), holder.agentLayout, holder.alreadyTV));
                holder.cancel.setOnClickListener(new MyClickListener(2, data.getAccountId(), holder.agentLayout, holder.alreadyTV));
            } else if (type == TYPE_AGREED) {
                holder.titile.setText(getResources().getString(R.string.add_friend_apply));
                holder.agentLayout.setVisibility(View.GONE);
                holder.alreadyTV.setVisibility(View.VISIBLE);
                holder.refusedTV.setVisibility(View.GONE);
                holder.alreadyTV.setText(getResources().getString(R.string.already_agreed));
            } else if (type == TYPE_REFUSED) {
                holder.titile.setText(getResources().getString(R.string.add_friend_apply));
                holder.agentLayout.setVisibility(View.GONE);
                holder.alreadyTV.setVisibility(View.VISIBLE);
                holder.refusedTV.setVisibility(View.GONE);
                holder.alreadyTV.setText(getResources().getString(R.string.already_refused));
            } else if (type == TYPE_REFUSED_NOTIFY) {
                holder.titile.setText(getResources().getString(R.string.friend_notify));
                holder.agentLayout.setVisibility(View.GONE);
                holder.alreadyTV.setVisibility(View.GONE);
                holder.refusedTV.setVisibility(View.VISIBLE);
            }
            // 增加用户信息点击
            holder.headIV.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    ActivityUtils.intoHeadInfoActivity(data.getUserInfo().accountId, mContext);
                }
            });
            // 增加用户信息点击
            holder.headInfoLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    ActivityUtils.intoHeadInfoActivity(data.getUserInfo().accountId, mContext);
                }
            });
            return convertView;
        }

        private class MyClickListener implements OnClickListener {

            private int index = 0;
            private int ID;
            private LinearLayout layout;
            private TextView tv;

            public MyClickListener(int index, int id, LinearLayout layout, TextView tv) {
                this.index = index;
                this.ID = id;
                this.layout = layout;
                this.tv = tv;
            }

            @Override
            public void onClick(View v) {
                if (1 == index) {
                    tv.setVisibility(View.VISIBLE);
                    layout.setVisibility(View.GONE);
                    tv.setText(getResources().getString(R.string.already_agreed));
                    confirm(ID, 2);
                } else if (2 == index) {
                    tv.setVisibility(View.VISIBLE);
                    layout.setVisibility(View.GONE);
                    tv.setText(getResources().getString(R.string.already_refused));
                    confirm(ID, 3);
                }
            }

        }

        class Holder extends UserInfoHolder {
//            public TextView name;
//            public ImageView head;
//            public TextView label;
//            public ImageView sexIV;
//            public ImageView addV;
            public TextView cancel;
            public TextView confirm;
            public TextView alreadyTV;
            public LinearLayout agentLayout;
            public TextView titile;
            public TextView refusedTV;
//            public LinearLayout headLayout;
        }

    }

    @Override
    public void onFriendConfirmFailure(int errorCode, String errorMsg) {
        //
    }

    @Override
    public void onFriendConfirmSuccess() {
        //
    }

    @Override
    public void onNoticeHandListFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
        pullListView.onRefreshComplete(false, false);
        waittingLayout.setVisibility(View.VISIBLE);
        waittingProBar.setVisibility(View.GONE);
        waittingTV.setText(errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onNoticeHandListSuccess(List<NoticeHandData> list) {
        waittingLayout.setVisibility(View.GONE);
        // TODO Auto-generated method stub
        pullListView.onRefreshComplete(false, false);
        if (null == list)
            return;
        adapter.addData(list);
        mList = adapter.getList();
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeNoticeHandListListener(this);
        }
        if (null != fcManager) {
            fcManager.removeFriendConfirmListener(this);
        }
    }
}
